#include "joinrule.h"

#include "../documents/data/graphicdata.h"
#include "../documents/swpprocessdocument.h"
#include "../editors/items/graphicitemcommon.h"
#include "../utils/modelvalidator.h"

#include <gdmodelquerymaker.h>
#include <ieditoritem.h>

#include <QtGui/QAction>

using namespace core;
using namespace swp;

JoinRule::JoinRule() : QObject(0), IValidatorRule(),
    m_action(0),
    m_lastData(0),
    m_notPassed()
{
    m_action = new QAction("", this);

    connect(m_action, SIGNAL(triggered()),
        this, SLOT(selectNotPassedItems()));
}

JoinRule::~JoinRule()
{

}

bool JoinRule::isProjectWide() const
{
    return false;
}

bool JoinRule::validate(
    const QSharedPointer<IContainerDocument>& document,
    QAction*& reportClickAction, QString& reportText) const
{
    return false;
}

bool JoinRule::validate(const QSharedPointer<IDocument>& document,
    QAction*& reportClickAction, QString& reportText) const
{
    bool ret = true;

    GraphicData* data = dynamic_cast<GraphicData* >(document->data());

    Q_ASSERT(data != 0); // GraphicData expected

    m_lastData = data;
    m_notPassed.clear();

    reportClickAction = m_action;

    GDModelQueryMaker queryMaker(*data);

    const QList<IGraphicEditorItem* > joins =
        queryMaker.getItems(SWP_JOIN_ITEM);


    foreach (IGraphicEditorItem* join, joins)
    {
        const QList<ConnectionData> connections = join->connections();

        int count = 0;

        foreach (const ConnectionData& connection, connections)
        {
            if (connection.To == join)
            {
                ++count;
            }
        }

        ret = ret && count == 2;

        if (count != 2)
        {
            m_notPassed.append(join);
        }
    }

    reportText = QObject::tr("Join item should have two incoming transitions");

    return ret;
}

// private slots
void JoinRule::selectNotPassedItems()
{
    if (m_lastData != 0)
    {
        ModelValidator::getInstance()->actionAboutToTrigger(m_action);

        m_lastData->clearSelection();

        foreach (IGraphicEditorItem* item, m_notPassed)
        {
            QGraphicsItem* _item  = dynamic_cast<QGraphicsItem* >(item);

            Q_ASSERT(_item != 0); // shouldn't happen

            _item->setSelected(true);
        }
    }
}
